package com.perye.dokit.service.impl;

import com.perye.dokit.dto.DictDetailDto;
import com.perye.dokit.entity.User;
import com.perye.dokit.mapper.dao.DaoSupport;
import com.perye.dokit.query.DictDetailQueryCriteria;
import com.perye.dokit.entity.DictDetail;
import com.perye.dokit.mapper.DictDetailMapper;
import com.perye.dokit.repository.DictDetailRepository;
import com.perye.dokit.service.DictDetailService;
import com.perye.dokit.utils.PageUtil;
import com.perye.dokit.utils.QueryHelp;
import com.perye.dokit.utils.SecurityUtils;
import com.perye.dokit.utils.ValidationUtil;
import com.perye.dokit.utils.pageData.PageData;
import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@CacheConfig(cacheNames = "dictDetail")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictDetailServiceImpl implements DictDetailService {

    @Resource(name = "daoSupport")
    private DaoSupport dao;

    private final DictDetailRepository dictDetailRepository;

    private final DictDetailMapper dictDetailMapper;

    public DictDetailServiceImpl(DictDetailRepository dictDetailRepository, DictDetailMapper dictDetailMapper) {
        this.dictDetailRepository = dictDetailRepository;
        this.dictDetailMapper = dictDetailMapper;
    }

    @Override
    @Cacheable
    public Map<String,Object> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
        Page<DictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dictDetailMapper::toDto));
    }

    @Override
    public <T> T queryDictDetailByName(String name, String type) {
        PageData pageInfo = new PageData();//存放传入参数进行数据查询
        List<PageData> dictList = new ArrayList<>();//将查出来的字典以list的形式进行存储
        Map<String, String> dictMap = new HashMap<String, String>();//将查出来的字典以map的形式进行存储

        try {
            //判断传入参数是否为空
            if (StringUtils.isNotBlank(name)) {
                pageInfo.put("name", name);//将传入参数存放到对象中进行查询，方便以后扩展
                dictList = (List<PageData>) dao.findForList("DictDetailMapper.queryDictDetailByName", pageInfo);
                if ("map".equals(type) && !CollectionUtils.isEmpty(dictList)) {
                    for (PageData dict : dictList) {
                        String label = dict.getString("label");
                        String value = dict.getString("value");
                        dictMap.put(value, label);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if ("map".equals(type)) {
            return (T) dictMap;
        }
        return (T) dictList;
    }

    @Override
    @Cacheable(key = "#p0")
    public DictDetailDto findById(Long id) {
        DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new);
        ValidationUtil.isNull(dictDetail.getId(),"DictDetail","id",id);
        return dictDetailMapper.toDto(dictDetail);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public DictDetailDto create(DictDetail resources) {
        return dictDetailMapper.toDto(dictDetailRepository.save(resources));
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void update(DictDetail resources) {
        DictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(DictDetail::new);
        ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId());
        resources.setId(dictDetail.getId());
        dictDetailRepository.save(resources);
    }

    @Override
    @CacheEvict(allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        dictDetailRepository.deleteById(id);
    }
}
